package com.eedi.framework.oauth2.controller.sys;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.eedi.framework.common.enums.CommonStatusEnum;
import com.eedi.framework.common.pojo.CommonResult;
import com.eedi.framework.oauth2.controller.sys.vo.auth.SysAuthLoginReq;
import com.eedi.framework.oauth2.controller.sys.vo.auth.SysAuthLoginResp;
import com.eedi.framework.oauth2.controller.sys.vo.auth.SysAuthPermissionInfoResp;
import com.eedi.framework.oauth2.convert.SysAuthConvert;
import com.eedi.framework.oauth2.service.SysAuthService;
import com.eedi.framework.oauth2.service.SysOAuth2ClientService;
import com.eedi.framework.security.core.util.SecurityFrameworkUtils;
import com.eedi.framework.logger.enmus.SysLoginLogTypeEnum;
import com.eedi.framework.permission.dal.dataobject.SysRoleDO;
import com.eedi.framework.permission.service.SysPermissionService;
import com.eedi.framework.user.controller.sys.vo.SysUserLoginInfoResp;
import com.eedi.framework.user.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.eedi.framework.security.config.SecurityProperties;
import com.eedi.framework.permission.dal.dataobject.SysMenuDO;
import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import static com.eedi.framework.common.pojo.CommonResult.success;
import static com.eedi.framework.common.util.collection.CollectionUtils.convertSet;
import static com.eedi.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static com.eedi.framework.security.core.util.SecurityFrameworkUtils.getTenantId;

@Tag(name = "系统界面 - 认证")
@RestController
@RequestMapping("/auth")
@Validated
@Slf4j
public class SysAuthController {
    @Resource
    SysAuthService sysAuthService;
    @Resource
    SecurityProperties securityProperties;

    @Resource
    SysUserService sysUserService;

    @Resource
    SysPermissionService sysPermissionService;

    @Resource
    SysOAuth2ClientService sysOAuth2ClientService;


    @PostMapping("/login")
    @PermitAll
    @Operation(summary = "使用账号密码登录")
    public CommonResult<SysAuthLoginResp> login(@RequestBody @Valid SysAuthLoginReq reqVO) {
        //根据当前租户ID获取clientId，仅适用于单体式架构
        if (StrUtil.isBlank(reqVO.getSysClientId())){
            reqVO.setSysClientId(sysOAuth2ClientService.getClientIdBySysTenantId(getTenantId()));
        }
        return success(sysAuthService.login(reqVO));
    }

    @PostMapping("/logout")
    @PermitAll
    @Operation(summary = "登出系统")
    public CommonResult<Boolean> logout(HttpServletRequest request) {
        String token = SecurityFrameworkUtils.obtainAuthorization(request,
                securityProperties.getTokenHeader(), securityProperties.getTokenParameter());
        if (StrUtil.isNotBlank(token)) {
            sysAuthService.logout(token, SysLoginLogTypeEnum.LOGOUT_SELF);
        }
        return success(true);
    }

    @PostMapping("/refresh-token")
    @PermitAll
    @Operation(summary = "刷新令牌")
    @Parameter(name = "refreshToken", description = "刷新令牌", required = true)
    public CommonResult<SysAuthLoginResp> refreshToken(@RequestParam("refreshToken") String refreshToken
    ) {
        //根据当前租户ID获取clientId，仅适用于单体式架构
        String sysClientId = sysOAuth2ClientService.getClientIdBySysTenantId(getTenantId());
        return success(sysAuthService.refreshToken(refreshToken,sysClientId));
    }

    @GetMapping("/get-permission-info")
    @Operation(summary = "获取登录用户的权限信息")
    public CommonResult<SysAuthPermissionInfoResp> getPermissionInfo() {
        // 1.1 获得用户信息
        SysUserLoginInfoResp logininfo = sysUserService.selectBySysUserId(getLoginUserId());
        if (logininfo == null) {
            return success(null);
        }

        // 1.2 获得角色列表
        Set<String> roleIds = sysPermissionService.getUserRoleIdListByUserId(getLoginUserId());
        if (CollUtil.isEmpty(roleIds)) {
            return success(SysAuthConvert.INSTANCE.convert(logininfo, Collections.emptyList(), Collections.emptyList()));
        }
        List<SysRoleDO> roles = sysPermissionService.getRoleList(roleIds);
        // 移除禁用的角色
        roles.removeIf(role -> !CommonStatusEnum.ENABLE.equals(role.getSysRoleStatus()));

        // 1.3 获得菜单列表
        Set<String> menuIds = sysPermissionService.getRoleMenuListByRoleId(convertSet(roles, SysRoleDO::getSysRoleId));
        List<SysMenuDO> menuList = sysPermissionService.getMenuList(menuIds);
        // 移除禁用的菜单
        menuList.removeIf(menu -> !CommonStatusEnum.ENABLE.equals(menu.getSysMenuStatus()));

        // 2. 拼接结果返回
        return success(SysAuthConvert.INSTANCE.convert(logininfo, roles, menuList));
    }

    @GetMapping("/get-menu-info")
    @Operation(summary = "获取登录用户的菜单信息")
    public CommonResult<List<SysAuthPermissionInfoResp.MenuVO>> getMenuInfo() {
        // 1 获得角色列表
        Set<String> roleIds = sysPermissionService.getUserRoleIdListByUserId(getLoginUserId());
        List<SysRoleDO> roles = sysPermissionService.getRoleList(roleIds);
        // 2 移除禁用的角色
        roles.removeIf(role -> !CommonStatusEnum.ENABLE.equals(role.getSysRoleStatus()));
        // 3 获得菜单列表
        Set<String> menuIds = sysPermissionService.getRoleMenuListByRoleId(convertSet(roles, SysRoleDO::getSysRoleId));
        List<SysMenuDO> menuList = sysPermissionService.getMenuList(menuIds);
        // 4 移除禁用的菜单
        menuList.removeIf(menu -> !CommonStatusEnum.ENABLE.equals(menu.getSysMenuStatus()));

        // 2. 拼接结果返回
        return success(SysAuthConvert.INSTANCE.buildMenuTree(menuList));
    }

    // ========== 短信登录相关 ==========

//    @PostMapping("/sms-login")
//    @PermitAll
//    @Operation(summary = "使用短信验证码登录")
//    public CommonResult<AuthLoginRespVO> smsLogin(@RequestBody @Valid AuthSmsLoginReqVO reqVO) {
//        return success(authService.smsLogin(reqVO));
//    }

//    @PostMapping("/send-sms-code")
//    @PermitAll
//    @Operation(summary = "发送手机验证码")
//    public CommonResult<Boolean> sendLoginSmsCode(@RequestBody @Valid AuthSmsSendReqVO reqVO) {
//        authService.sendSmsCode(reqVO);
//        return success(true);
//    }

//    // ========== 社交登录相关 ==========
//
//    @GetMapping("/social-auth-redirect")
//    @PermitAll
//    @Operation(summary = "社交授权的跳转")
//    @Parameters({
//            @Parameter(name = "type", description = "社交类型", required = true),
//            @Parameter(name = "redirectUri", description = "回调路径")
//    })
//    public CommonResult<String> socialLogin(@RequestParam("type") Integer type,
//                                            @RequestParam("redirectUri") String redirectUri) {
//        return success(socialClientService.getAuthorizeUrl(
//                type, UserTypeEnum.ADMIN.getValue(), redirectUri));
//    }

//    @PostMapping("/social-login")
//    @PermitAll
//    @Operation(summary = "社交快捷登录，使用 code 授权码", description = "适合未登录的用户，但是社交账号已绑定用户")
//    public CommonResult<AuthLoginRespVO> socialQuickLogin(@RequestBody @Valid AuthSocialLoginReqVO reqVO) {
//        return success(authService.socialLogin(reqVO));
//    }
}
